package org.pizza.did.autoconfigure;

import org.pizza.did.api.IdGenerator;
import org.pizza.did.api.WorkerIdDistributor;
import org.pizza.did.properties.IdProperties;
import org.pizza.did.snowflake.SnowflakeIdGenerator;
import org.pizza.did.snowflake.listener.WorkIdChangeListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;

/**
 * @author 高巍
 * @since  2020/10/13 3:40 下午
 */
@Configuration
@EnableConfigurationProperties({IdProperties.class})
@Import({ZookeeperDistributorConfiguration.class, RedisDistributorConfiguration.class, MysqlDistributorConfiguration.class})
public class IdGeneratorAutoConfiguration  {
    private static final Logger log = LoggerFactory.getLogger(IdGeneratorAutoConfiguration.class);
    private final IdProperties idProperties;
    private ConfigurableApplicationContext applicationContext;
    public IdGeneratorAutoConfiguration(IdProperties idProperties) {
        this.idProperties = idProperties;
    }

    @Bean
    public IdGenerator idGenerator(WorkerIdDistributor workerIdDistributor) {
        this.idProperties.setWorkId(workerIdDistributor.distribute());
        return new SnowflakeIdGenerator(this.idProperties.getWorkId(), this.idProperties.getDataCenterId());
    }

    @Bean
    public WorkIdChangeListener workIdChangeListener(IdGenerator idGenerator,WorkerIdDistributor workerIdDistributor){
        return new WorkIdChangeListener(workerIdDistributor, idGenerator);
    }
}
